package com.nus.fellowmark.modules.assignment.service.impl;

import com.nus.fellowmark.dao.AssignmentDao;
import com.nus.fellowmark.entity.AssignmentEntity;
import com.nus.fellowmark.modules.assignment.dto.AssignmentDTO;
import com.nus.fellowmark.modules.assignment.dto.ConfigDTO;
import com.nus.fellowmark.modules.assignment.dto.RubricDTO;
import com.nus.fellowmark.modules.assignment.dto.UpdateAssignmentDTO;
import com.nus.fellowmark.modules.assignment.service.AssignmentService;
import com.nus.fellowmark.modules.assignment.service.GradeCalculationConfigService;
import com.nus.fellowmark.modules.assignment.service.RubricService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nus.fellowmark.common.utils.PageUtils;
import com.nus.fellowmark.common.utils.Query;


@Service("assignmentService")
public class AssignmentServiceImpl extends ServiceImpl<AssignmentDao, AssignmentEntity> implements AssignmentService {

    @Autowired
    AssignmentDao assignmentDao;

    @Autowired
    RubricService rubricService;

    @Autowired
    GradeCalculationConfigService gradeCalculationConfigService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AssignmentEntity> page = this.page(
                new Query<AssignmentEntity>().getPage(params),
                new QueryWrapper<AssignmentEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public AssignmentEntity addAssignment(AssignmentDTO assignmentDTO) {
        AssignmentEntity assignmentEntity = new AssignmentEntity();
        BeanUtils.copyProperties(assignmentDTO, assignmentEntity);
        boolean success = assignmentDao.insert(assignmentEntity) > 0;
        if (success) {
            gradeCalculationConfigService.initConfig(assignmentEntity.getId());
        }
        return assignmentEntity;
    }

    @Override
    public void updateAssignment(UpdateAssignmentDTO assignmentDTO) {
        AssignmentEntity assignmentEntity = new AssignmentEntity();
        BeanUtils.copyProperties(assignmentDTO,assignmentEntity);
        assignmentDao.updateById(assignmentEntity);
    }

    @Override
    public List<AssignmentEntity> listAssignment(Integer moduleId) {
        QueryWrapper<AssignmentEntity> queryWrapper = new QueryWrapper<AssignmentEntity>().eq("module_id", moduleId);
        return assignmentDao.selectList(queryWrapper);
    }

}
